package com.fire.communication.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fire.communication.common.base.BaseService;
import com.fire.communication.model.notice.NoticeContacts;
import com.fire.communication.model.notice.NoticeGroup;
import com.fire.communication.model.notice.NoticeGroupContact;
import com.fire.communication.model.notice.NoticeRecord;
import com.fire.communication.support.model.RespEntity;
import com.fire.communication.support.mybatisplus.QueryWrapper;
import com.fire.communication.support.utils.requestutil.HttpRequestUtil;
import com.fire.communication.web.mapper.notice.NoticeContactsMapper;
import com.fire.communication.web.mapper.notice.NoticeGroupContactMapper;
import com.fire.communication.web.mapper.notice.NoticeGroupMapper;
import com.fire.communication.web.mapper.notice.NoticeRecordMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @Author: YangYu
 * @ClassName: NoticeService
 * @Date: Created in 9:39 2022/7/12
 * @Description:
 */
@Service
public class NoticeService extends BaseService {

    @Resource
    private NoticeGroupMapper noticeGroupMapper;
    @Resource
    private NoticeGroupContactMapper noticeGroupContactMapper;
    @Resource
    private NoticeContactsMapper noticeContactsMapper;
    @Resource
    private NoticeRecordMapper noticeRecordMapper;
    /**
     * @Author YangYu
     * @Description 联系组分页列表
     * @Date Created in 9:52 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeGroupListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        jsonParam.put("homeId",homeId);
        Page<NoticeGroup> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        IPage<NoticeGroup> pageList = noticeGroupMapper.noticeGroupListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * @Author YangYu
     * @Description 通知组新增、编辑
     * @Date Created in 10:19 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeGroupAddOrUpdate(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        NoticeGroup noticeGroup = new NoticeGroup();
        if (!jsonParam.containsKey("id")){
            noticeGroup.setId(UUID.randomUUID().toString());
            noticeGroup.setGroupName(jsonParam.getStr("groupName"));
            noticeGroup.setHomeId(homeId);
            noticeGroup.setRemark(jsonParam.getStr("remark"));
            noticeGroupMapper.insert(noticeGroup);
        }else {
            noticeGroup.setId(jsonParam.getStr("id"));
            noticeGroup.setGroupName(jsonParam.getStr("groupName"));
            noticeGroup.setHomeId(homeId);
            noticeGroup.setRemark(jsonParam.getStr("remark"));
            noticeGroupMapper.updateById(noticeGroup);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 分组删除
     * @Date Created in 10:26 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeGroupDel(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空");
        }else {
            int count = noticeGroupContactMapper.selectCount(new QueryWrapper<NoticeGroupContact>().eq("group_id",jsonParam.getStr("id")));
            if (count > 0){
                return RespEntity.fail("本组下存在联系人，无法删除");
            }
            noticeGroupMapper.deleteById(jsonParam.getStr("id"));
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 联系人分页列表
     * @Date Created in 10:34 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeContactsListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        jsonParam.put("homeId",homeId);
        Page<NoticeContacts> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        IPage<NoticeContacts> pageList = noticeContactsMapper.noticeContactsListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * @Author YangYu
     * @Description 联系人新增、编辑
     * @Date Created in 10:52 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeContactsAddOrUpdate(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        NoticeContacts noticeContacts = new NoticeContacts();
        String id = "";
        if (!jsonParam.containsKey("id")){
            id = UUID.randomUUID().toString();
            noticeContacts.setId(id);
            noticeContacts.setName(jsonParam.getStr("name"));
            noticeContacts.setPhone(jsonParam.getStr("phone"));
            noticeContacts.setHomeId(homeId);
            noticeContacts.setRemark(jsonParam.getStr("remark"));
            noticeContactsMapper.insert(noticeContacts);
        }else {
            id = jsonParam.getStr("id");
            noticeContacts.setId(id);
            noticeContacts.setName(jsonParam.getStr("name"));
            noticeContacts.setPhone(jsonParam.getStr("phone"));
            noticeContacts.setHomeId(homeId);
            noticeContacts.setRemark(jsonParam.getStr("remark"));
            noticeContactsMapper.updateById(noticeContacts);
        }
        return RespEntity.success(id);
    }
    /**
     * @Author YangYu
     * @Description 联系人删除
     * @Date Created in 10:26 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeContactsDel(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空");
        }else {
            noticeContactsMapper.deleteById(jsonParam.getStr("id"));
            noticeGroupContactMapper.delete(new QueryWrapper<NoticeGroupContact>().eq("contacts_id",jsonParam.getStr("id")));
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 组内联系人分页列表
     * @Date Created in 10:34 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeGroupContactsListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        jsonParam.put("homeId",homeId);
        Page<NoticeGroupContact> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        IPage<NoticeGroupContact> pageList = noticeGroupContactMapper.noticeGroupContactsListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * @Author YangYu
     * @Description 联系人绑定分组
     * @Date Created in 11:20 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeGroupContactsAdd(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        NoticeGroupContact noticeGroupContact = new NoticeGroupContact();
        String[] contactsIds = jsonParam.getStr("contactsId").split(",");

        for (String contactsId : contactsIds){
            noticeGroupContact.setGroupId(jsonParam.getStr("groupId"));
            noticeGroupContact.setContactsId(contactsId);
            noticeGroupContactMapper.insert(noticeGroupContact);
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 组内删除联系人
     * @Date Created in 11:30 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity noticeGroupContactsDel(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isNotBlank(jsonParam.getStr("groupId")) && StrUtil.isNotBlank(jsonParam.getStr("contactsId"))){
            noticeGroupContactMapper.delete(new QueryWrapper<NoticeGroupContact>().eq("group_id",jsonParam.getStr("groupId")).eq("contacts_id",jsonParam.getStr("contactsId")));
        }else {
            return RespEntity.fail("groupId或contactsId不能为空");
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 记录分页列表
     * @Date Created in 8:56 2022/7/15
     * @Param [jsonParam]
     */

    public RespEntity noticeRecordListPage(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        Page<NoticeRecord> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        IPage<NoticeRecord> pageList = noticeRecordMapper.noticeRecordListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }
    /**
     * @Author YangYu
     * @Description 短信语音通知
     * @Date Created in 12:45 2022/7/12
     * @Param [jsonParam]
     */

    public RespEntity sMSVoiceNotice(JSONObject jsonParam) throws IOException {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        System.out.println("jsonParam:"+jsonParam.toString());
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        //通知方式 1短信 2语音 3 语音和短信
        String noticeType = jsonParam.getStr("noticeType");
        //时间
        String date = jsonParam.getStr("date");
        //通知内容
        String content =   jsonParam.getStr("content");
        //联系人
        String contact = jsonParam.getStr("contact");
        //联系电话
        String contactPhone = jsonParam.getStr("contactPhone");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("date",date);
        jsonObject.put("name",":"+contact);
        jsonObject.put("ptone",":"+contactPhone);
        jsonParam.put("TemplateParam",jsonObject.toString());
        jsonParam.put("msg","您好，请于"+date+content+"，联系人:"+contact+"，联系电话:"+contactPhone+"，收到请回复1");
        jsonParam.put("time",System.currentTimeMillis()/1000);
        //批量添加记录
        List<NoticeRecord> noticeRecordList = new ArrayList<>();
        //全组通知
        if (jsonParam.containsKey("groupId")){
            List<NoticeGroupContact> phoneList = noticeGroupContactMapper.getPhoneList(jsonParam.getStr("groupId"));
            for (NoticeGroupContact noticeGroupContact : phoneList){
                NoticeRecord noticeRecord = new NoticeRecord();
                jsonParam.put("phone",noticeGroupContact.getStr("phone"));
                //短信
                //aliCommunicationsService.banLingSendSms(jsonParam);
                noticeRecord.setId(UUID.randomUUID().toString());
                noticeRecord.setGroupId(jsonParam.getStr("groupId"));
                noticeRecord.setContacts(noticeGroupContact.getStr("name"));
                noticeRecord.setPhone(noticeGroupContact.getStr("phone"));
                noticeRecord.setState(2);
                noticeRecord.setContactsId(noticeGroupContact.getStr("id"));
                noticeRecord.setTime(DateUtil.date());
                noticeRecord.setType(1);
                noticeRecordList.add(noticeRecord);
                //语音
                //aliCommunicationsService.noticeSendVms(jsonParam);
                noticeRecord = new NoticeRecord();
                noticeRecord.setId(UUID.randomUUID().toString());
                noticeRecord.setGroupId(jsonParam.getStr("groupId"));
                noticeRecord.setContacts(noticeGroupContact.getStr("name"));
                noticeRecord.setPhone(noticeGroupContact.getStr("phone"));
                noticeRecord.setContactsId(noticeGroupContact.getStr("id"));
                noticeRecord.setState(4);
                noticeRecord.setTime(DateUtil.date());
                noticeRecord.setType(2);
                noticeRecordList.add(noticeRecord);
            }
            //批量新增记录
            noticeRecordMapper.insertZB(noticeRecordList);
        //单个通知
        }else {
            String[] ids = jsonParam.getStr("contactsId").split(",");
            List<NoticeContacts> noticeContactsList = noticeContactsMapper.getContactsList(ids);
            for (NoticeContacts noticeContacts : noticeContactsList){
                jsonParam.put("phone",noticeContacts.getPhone());
                //短信
                //aliCommunicationsService.banLingSendSms(jsonParam);
                //语音
                //aliCommunicationsService.noticeSendVms(jsonParam);
            }
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 根据手机号更新回复状态
     * @Date Created in 16:15 2022/7/15
     * @Param [jsonParam]
     */

    public RespEntity noticeUpdateState(JSONObject jsonParam) throws IOException {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        NoticeRecord noticeRecord = new NoticeRecord();
        UpdateWrapper<NoticeRecord> updateWrapper = new UpdateWrapper<>();
        if (jsonParam.containsKey("voiceprompt_callback")){
            String result = jsonParam.getJSONObject("voiceprompt_callback").getStr("result");
            if (!result.equals("0")){
                updateWrapper.eq("phone",jsonParam.getJSONObject("voiceprompt_callback").getStr("mobile")).eq("type",2).set("state", "1");
            }
        }else if (jsonParam.containsKey("text")){
            updateWrapper.eq("phone",jsonParam.getStr("mobile")).eq("type",1).set("state", "3");
        }else {
            return RespEntity.success();
        }
        noticeRecordMapper.update(noticeRecord,updateWrapper);
        return RespEntity.success();
    }
}
